package com.wangyadong.hobby.schedule.jobtask.javasync.semphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2019/1/2219:41
 **/
public class SemaphoreExample2 {

    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(2);
        for (int i = 0; i < 4; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " in ");
                try {
                    semaphore.acquire(2);
                    System.out.println(Thread.currentThread().getName() + " get the lock");
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release(2);
                    System.out.println(Thread.currentThread().getName() + " RELEASE ");
                }
                System.out.println(Thread.currentThread().getName() + " out ");
            }).start();
        }


        while (true) {
            System.out.println("AR ->" + semaphore.availablePermits());
            System.out.println("QL-->" + semaphore.getQueueLength());
            TimeUnit.SECONDS.sleep(1);
        }
    }
}
